package com.myway.core.jersey.filter;
import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;

import org.apache.log4j.Logger;
import org.glassfish.jersey.internal.util.Base64;

import com.myway.annocation.RequestFilter;
/**
 * @ClassName: CORSRequestFilter <br/>
 * @Description: Filter <br/>
 * @CreateDate: 2016年4月27日 下午4:50:44 <br/>
 * @author jiangyang
 * @version V1.0
 */
@Provider 
@RequestFilter
public class CORSRequestFilter implements ContainerRequestFilter {
	
	private Logger log=Logger.getLogger(CORSRequestFilter.class);
	@Override
	public void filter(ContainerRequestContext requestContext) throws IOException {

		String authHeader = requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); 
		log.info("Rest URI:"+requestContext.getUriInfo().getRequestUri());
		if (authHeader != null && authHeader.startsWith("Basic")) {
            String decoded = new String(Base64.decode(authHeader.substring(6).getBytes()), "UTF-8");
            final String[] split = decoded.split(":");
            final String username = split[0];
            final String pwd = split[1];
            log.info("Rest Basic:"+username+"/"+pwd);
            if ("admin".equals(username)){
            	//String inputParam = this.inputStreamToString(requestContext.getEntityStream());
            	//log.info("Rest Param:"+inputParam);
                requestContext.setSecurityContext(new SecurityContext() {
                    @Override
                    public Principal getUserPrincipal() {
                        return new Principal() {
                            @Override
                            public String getName() {
                                return username;
                            }
                        };
                    }

                    @Override
                    public boolean isUserInRole(String role) {
                    	if("admin".equals(role)){
                    		return true;
                    	}else{
                    		return false;
                    	}
                    }

                    @Override
                    public boolean isSecure() {
                        return false;
                    }

                    @Override
                    public String getAuthenticationScheme() {
                        return "BASIC";
                    }
                });
                
            }else{
            	requestContext.abortWith(Response
    					.status(Response.Status.BAD_REQUEST)
    					.entity("Not Recognized Client").build());
            }
		}else{
			requestContext.abortWith(Response
					.status(Response.Status.BAD_REQUEST)
					.entity("Not Recognized Client").build());
		}
		/*MultivaluedMap<String, String> headers = requestContext.getHeaders();
		List<String> client=headers.get("client-name");
		if (client== null||!"yang".equals(client.get(0))) {
			requestContext.abortWith(Response
					.status(Response.Status.BAD_REQUEST)
					.entity("Not Recognized Client").build());
		}*/
	}
	
	
	public String inputStreamToString(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n, "UTF-8"));
        }
        return out.toString();
}
 
}

